package com.zhihaoliang.coroutine.buss.net.ui

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.zhihaoliang.coroutine.buss.net.callback.IUserLoadData
import com.zhihaoliang.coroutine.buss.net.data.NetRepository
import com.zhihaoliang.coroutine.util.log
import kotlinx.coroutines.*

/**
 * @author 支豪亮
 * @date 2022/10/13 17:28
 * @des 主页面的ViewModel
 */
class NetViewModel(application: Application) : AndroidViewModel(application) {

    private val mainRepository: NetRepository = NetRepository()

    private var spinnerSelectedIndex = 0

    private var startTime: Long = 0L



    /**
     * 数据加载的方式
     */
    val spinnerSelIndex: Int
        get() = spinnerSelectedIndex

    /**
     * 耗时操作打印
     */
    fun showUseTime() = log("耗时：${System.currentTimeMillis() - startTime}")


    /**
     * 数据加载
     */
    fun loadData(userLoadData: IUserLoadData) {
        startTime = System.currentTimeMillis()
        when (spinnerSelectedIndex) {
            1 -> loadContributorsCallbacks(userLoadData)
            2 -> loadContributorsSuspend(userLoadData)
            3 -> loadContributorsConcurrent(userLoadData)
            4 -> loadContributorsProgress(userLoadData)
            5 -> loadContributorsChannels(userLoadData)
            else -> loadContributorsBlocking(userLoadData)
        }
    }

    fun setSpinnerIndex(spinnerIndex: Int) {
        spinnerSelectedIndex = spinnerIndex
    }

    private fun loadContributorsBlocking(userLoadData: IUserLoadData) {
        mainRepository.loadContributorsBlocking {
            userLoadData.onUserLoad(it)
        }
    }

    private fun loadContributorsCallbacks(userLoadData: IUserLoadData) {
        mainRepository.loadContributorsCallbacks {
            userLoadData.onUserLoad(it)
        }
    }

    private fun loadContributorsSuspend(userLoadData: IUserLoadData) = viewModelScope.launch {
        mainRepository.loadContributorsSuspend(userLoadData)
    }

    private fun loadContributorsConcurrent(userLoadData: IUserLoadData) = viewModelScope.launch {
        mainRepository.loadContributorsConcurrent(userLoadData)
    }

    private fun loadContributorsProgress(userLoadData: IUserLoadData) = viewModelScope.launch {
        mainRepository.loadContributorsProgress(userLoadData)
    }

    private fun loadContributorsChannels(userLoadData: IUserLoadData) = viewModelScope.launch {
        mainRepository.loadContributorsChannels(userLoadData)
    }


}